const wxCharts = require('../../../utils/wxcharts.js');
var attendanceChart = null;

Page({
  data: {
    userInfo: {
      name: '王老师',
      department: '计算机科学学院'
    },
    stats: {
      studentCount: 120,
      attendanceRate: 95,
      pendingLeaves: 3,
      unreadMessages: 5
    },
    pendingLeaves: [
      { id: 1, studentName: '张三', studentId: '2023001', type: '事假', startTime: '2023-09-15', endTime: '2023-09-16', days: 2, reason: '家中有事' },
      { id: 2, studentName: '李四', studentId: '2023002', type: '病假', startTime: '2023-09-16', endTime: '2023-09-18', days: 3, reason: '感冒发烧' },
      { id: 3, studentName: '王五', studentId: '2023003', type: '事假', startTime: '2023-09-17', endTime: '2023-09-17', days: 1, reason: '办理银行卡' }
    ],
    attendanceStats: {
      checkedIn: 110,
      late: 5,
      absent: 3,
      leave: 2
    },
    notices: [], // 添加通知数据数组
    // 添加天气数据到 data 中
    weather: {
      temp: '--°C',
      condition: '加载中',
      city: '福州'
    }
  },

  onLoad: function() {
    // 获取用户信息
    this.fetchUserInfo();
    
    // 获取统计数据
    this.fetchStats();
    
    // 获取待审批请假
    this.fetchPendingLeaves();
    
    // 获取考勤统计
    this.fetchAttendanceStats();
    
    // 获取通知公告
    this.fetchNotices();

    // 获取天气信息
    this.fetchWeather();
  },
  
  onShow: function() {
    // 页面显示时刷新数据
    this.fetchPendingLeaves();
    this.fetchStats();
    
    // 刷新通知公告
    this.fetchNotices();
  },
  
  onReady: function() {
    // 页面渲染完成后绘制图表
    this.drawAttendanceChart();
  },
  
  // 获取用户信息
  fetchUserInfo: function() {
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    } else {
      wx.request({
        url: 'http://localhost:3000/api/users/profile',
        method: 'GET',
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200) {
            this.setData({
              userInfo: res.data
            });
            
            // 缓存用户信息
            app.globalData.userInfo = res.data;
          }
        }
      });
    }
  },
  
  // 获取统计数据
  fetchStats: function() {
    wx.request({
      url: 'http://localhost:3000/api/counselor/stats',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            stats: res.data
          });
        }
      },
      fail: () => {
        // 使用模拟数据
        this.setData({
          stats: {
            studentCount: 5,
            attendanceRate: 20,
            pendingLeaves: 1,
            unreadMessages: 5
          }
        });
      }
    });
  },
  
  // 获取待审批请假
  fetchPendingLeaves: function() {
    wx.request({
      url: 'http://localhost:3000/api/counselor/leaves/pending',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            pendingLeaves: res.data
          });
        }
      },
      fail: () => {
        // 使用模拟数据
        this.setData({
          pendingLeaves: [
            { id: 1, studentName: '石净', studentId: '2025001', type: '事假', startTime: '2025-04-19', endTime: '2025-04-19', days: 1, reason: '家中有事' }

          ]
        });
      }
    });
  },
  
  // 获取考勤统计
  fetchAttendanceStats: function() {
    wx.request({
      url: 'http://localhost:3000/api/counselor/attendance/stats',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            attendanceStats: res.data
          });
          
          // 更新图表
          this.drawAttendanceChart();
        }
      },
      fail: () => {
        // 使用模拟数据
        this.setData({
          attendanceStats: {
            checkedIn: 1,
            late: 4,
            absent: 0,
            leave: 0
          }
        });
        
        // 更新图表
        this.drawAttendanceChart();
      }
    });
  },
  
  // 绘制考勤图表
  drawAttendanceChart: function() {
    const stats = this.data.attendanceStats;
    
    try {
      attendanceChart = new wxCharts({
        canvasId: 'attendanceChart',
        type: 'pie',
        series: [{
          name: '已签到',
          data: stats.checkedIn,
          color: '#52c41a'
        }, {
          name: '迟到',
          data: stats.late,
          color: '#faad14'
        }, {
          name: '缺勤',
          data: stats.absent,
          color: '#ff4d4f'
        }, {
          name: '请假',
          data: stats.leave,
          color: '#d9d9d9'
        }],
        width: 300,
        height: 200,
        dataLabel: false
      });
    } catch (e) {
      console.error('绘制图表失败', e);
    }
  },
  
  // 查看请假详情
  viewLeaveDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/qingjiaxiangqing/qingjiaxiangqing?id=${id}`
    });
  },
  
  // 页面导航
  navigateTo: function(e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    });
  },

  // 获取通知公告 - 移动到Page对象内部
  fetchNotices: function() {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/notices`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            notices: res.data.slice(0, 3) // 只显示最新的3条通知
          });
        }
      },
      fail: () => {
        // 模拟数据
        this.setData({
          notices: [
            {
              id: 1,
              title: '关于2023-2024学年第一学期期末考试安排的通知',
              publishTime: '2023-12-10'
            },
            {
              id: 2,
              title: '关于寒假放假安排的通知',
              publishTime: '2023-12-08'
            },
            {
              id: 3,
              title: '关于开展学生心理健康调查的通知',
              publishTime: '2023-12-05'
            }
          ]
        });
      }
    });
  },

  // 查看通知详情 - 移动到Page对象内部
  viewNoticeDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/counselor/notice/detail/detail?id=${id}`
    });
  },
  
  // 添加获取天气的方法
  fetchWeather: function() {
    wx.request({
      url: 'https://api.seniverse.com/v3/weather/now.json',
      method: 'GET',
      data: {
        key: 'SIij8E6v5NGGp0nYK',
        location: 'fujianfuzhou',
        language: 'zh-Hans',
        unit: 'c'
      },
      success: (res) => {
        if (res.data && res.data.results && res.data.results[0]) {
          const weatherData = res.data.results[0];
          this.setData({
            weather: {
              temp: `${weatherData.now.temperature}°C`,
              condition: weatherData.now.text,
              city: weatherData.location.name
            }
          });
        }
      },
      fail: (err) => {
        console.error('获取天气信息失败：', err);
      }
    });
  }
});